package com.demo.chapter3lambda;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import com.demo.domain.Apple;
import com.demo.domain.Fruit;
import com.demo.domain.Orange;

/**构造函数的方法引用
 * 对于没有参数的构造方法，等同于() -> new Apple
 */
public class MethodReference2 {

	static Map<String, Function<Integer, Fruit>> map = new HashMap<>();
	static {
		map.put("apple", Apple::new);
		map.put("orange", Orange::new);
	}

	public void demo(){
		//调用public Apple()构造方法
		Supplier<Apple> a = () -> new Apple();
		Supplier<Apple> a2 = Apple::new;
		Apple apple = a2.get();//调用get方法返回apple实例

		//调用public Apple(int weight)构造方法
		Function<Integer, Apple> a3 = (Integer weight) -> new Apple(weight);
		Function<Integer, Apple> a4 = Apple::new;
		Apple apple2 = a4.apply(100);
		//调用public Apple(int weight)构造方法生成多个苹果
		List<Integer> weights = Arrays.asList(7, 3, 5, 8);
		List<Apple> apples = weights.stream().map(a4).collect(Collectors.toList());

		//调用public Apple(int weight, String color)构造方法
		BiFunction<Integer, String, Apple> c5 = (Integer weight, String color) -> new Apple(weight, color);
		BiFunction<Integer, String, Apple> c6 = Apple::new;
		Apple apple3 = c6.apply(100, "red");
	}

	//返回指定重量的指定水果
	public static Fruit getFruit(String fruit, Integer weight){
		return map.get(fruit).apply(weight);
	}

}
